package xyf.p04.tree;

import commons.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * ClassName: P0102_LevelOrder
 * Description:
 * Author: xyf
 * Date: 9/4/22 10:53 AM
 * Version: 1.0
 **/
public class P0102_LevelOrder
{
    public List<List<Integer>> levelOrder(TreeNode root)
    {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null)
        {
            return result;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (queue.size() > 0)
        {
            List<Integer> level = new ArrayList<>();
            int currentLevel = queue.size();
            for (int i = 0; i < currentLevel; i++)
            {
                TreeNode node = queue.poll();
                level.add(node.val);
                if (node.left != null)
                {
                    queue.offer(node.left);
                }
                if (node.right != null)
                {
                    queue.offer(node.right);
                }
            }
            result.add(level);
        }
        return result;
    }
}
